<script setup lang="ts">
import { computed } from 'vue'

import type { Tab } from '../../use-tabs'
import useTabs from '../../use-tabs'

interface Opt {
  name: 'back' | 'forward' | 'refresh'
  icon: string
  disable?: (tab: Tab) => boolean
}
const HISTORY_OPTS: Opt[] = [
  { name: 'back', icon: 'icon-zuojiantou', disable: (tab: Tab) => !tab.canGoBack },
  { name: 'forward', icon: 'icon-youjiantou', disable: (tab: Tab) => !tab.canGoForward },
  { name: 'refresh', icon: 'icon-shuaxin' }
]
const { tabs, activeTabIndex, startChangeTabHistory } = useTabs()
const activeTab = computed(() => tabs.value[activeTabIndex.value])

function handleClick(opt: Opt) {
  if (!activeTab.value || (opt.disable && opt.disable(activeTab.value))) {
    return
  }
  startChangeTabHistory(activeTab.value.webContentsId, opt.name)
}
</script>

<template>
  <div class="search-bar">
    <div class="search-bar__history">
      <span
        class="search-bar__history__opt"
        :class="{ disabled: !activeTab || (opt.disable && opt.disable(activeTab)) }"
        v-for="opt in HISTORY_OPTS"
        :key="opt.name"
        @click="handleClick(opt)"
      >
        <i :class="`iconfont ${opt.icon}`"></i>
      </span>
    </div>
    <input class="search-bar__input" :value="activeTab?.url" />
  </div>
</template>

<style scoped>
.search-bar {
  box-sizing: border-box;
  height: 44px;
  background: var(--bg-color-base);
  padding: var(--bar-padding);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-md);
}
.search-bar__history {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}
.search-bar__history__opt {
  display: inline-flex;
  width: var(--bar-height);
  height: var(--bar-height);
  border-radius: 50%;
  justify-content: center;
  align-items: center;
}
.search-bar__history__opt.disabled {
  color: var(--text-color-disabled);
}
.search-bar__history__opt:not(.disabled):hover {
  background: var(--bg-color-page);
}
.search-bar__input {
  box-sizing: border-box;
  width: 0;
  flex-grow: 1;
  height: var(--bar-height);
  border: none;
  border-radius: 17px;
  background: var(--color-gray-4);
  padding: 0 var(--spacing-lg);
}
.search-bar__input:focus-visible {
  outline: none !important;
}
</style>
